import { NextResponse } from 'next/server'
import acceptLanguage from 'accept-language'
import { fallbackLng, languages, cookieName } from './app/i18n/settings'
acceptLanguage.languages(languages)

export const config = {
  // matcher: '/:lng*'
  matcher: ['/((?!api|_next/static|_next/image|assets|favicon.ico|sw.js|.png$|.jpg$|.jpeg$|.gif$).*)']
}
export function middleware(req) {
  // 过滤静态资源
  const staticFileExtensions = [
    '.jpg', '.jpeg', '.png', '.gif', '.webp', // 图片文件
    '.css', '.js', '.ico', '.svg', '.woff', '.woff2', // 其他静态资源
    // 添加其他您想要过滤的静态资源文件扩展名
    '.mp4', '.webm', '.ogg', '.mp3', '.wav', '.flac', '.aac', // 音频文件
  ];
  const pathname = req.nextUrl.pathname;

  // 检查是否请求的是静态资源文件
  const isStaticFile = staticFileExtensions.some(ext => pathname.endsWith(ext));
  if (isStaticFile) {
    return NextResponse.next(); // 如果是静态资源，则不进行下面的语言重定向逻辑
  }

  let lng
  if (req.cookies.has(cookieName)) lng = acceptLanguage.get(req.cookies.get(cookieName).value)
  if (!lng) lng = acceptLanguage.get(req.headers.get('Accept-Language'))
  if (!lng) lng = fallbackLng

  // Redirect if lng in path is not supported
  if (
    !languages.some(loc => req.nextUrl.pathname.startsWith(`/${loc}`)) &&
    !req.nextUrl.pathname.startsWith('/_next')
  ) {
    return NextResponse.redirect(new URL(`/${lng}${req.nextUrl.pathname}`, req.url))
  }

  if (req.headers.has('referer')) {
    const refererUrl = new URL(req.headers.get('referer'))
    const lngInReferer = languages.find((l) => refererUrl.pathname.startsWith(`/${l}`))
    const response = NextResponse.next()
    if (lngInReferer) response.cookies.set(cookieName, lngInReferer)
    return response
  }
  if(pathname == `/${lng}`){
    return NextResponse.redirect(new URL(`/${lng}/page`, req.url))
  }
  if(pathname == `/`){
    return NextResponse.redirect(new URL(`/${lng}/page`, req.url))
  }

  return NextResponse.next()
}